//
//  EditCaseView.swift
//  SwiftuiUno
//
//  Created by baozi on 2023/11/28.
//

import SwiftUI

struct EditCaseView: View {
    @EnvironmentObject var camera: CaptureLogic
    @EnvironmentObject var route: Router
    @State private var title: String = ""
    @State private var subTitle: String = ""
    @State private var birthDate = Date()

    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }()
    
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack(spacing: 0) {
                VStack(spacing: 0) {
                    HStack {
                        Text("Title")
                            .font(.system(size: 12))
                            .frame(height: 12)
                            .foregroundColor(Color.gray)
                            .padding()
                        Spacer()
                    }
                    TextField("Please input title", text: $title) {
                        
                    }
                    .padding()
                    .background(Color.gray.opacity(0.8))
                    .foregroundColor(Theme.color.primaryBackgroundColor)
                    .cornerRadius(12)
                    .padding(.horizontal)
                }
                
                VStack(spacing: 0) {
                    HStack {
                        Text("Remark")
                            .frame(height: 12)
                            .font(.system(size: 12))
                            .foregroundColor(Color.gray)
                            .padding()
                        Spacer()
                    }
                    TextField("Please input remark", text: $subTitle) {
                        
                    }
                    .textFieldStyle(.plain)
                    .padding()
                    .background(Color.gray.opacity(0.8))
                    .foregroundColor(Theme.color.primaryBackgroundColor)
                    .cornerRadius(12)
                    .padding(.horizontal)
                }
                
                DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
                    Text("Select a date")
                        .foregroundColor(.gray)
                }
                .padding()
                
                TabView {
                    ForEach(camera.picDatas) { data in
                        if let image = UIImage(data: data.datas) {
                            Image(uiImage: image)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .padding()
                                .cornerRadius(12)
                                .contextMenu {
                                    Button {
                                        camera.picDatas.removeAll { preData in
                                            preData.id == data.id
                                        }
                                    } label: {
                                        HStack {
                                            Text("删除")
                                            Image(systemName: "trash")
                                        }
                                    }
                                }
                        }
                    }
                }
                .tabViewStyle(.page(indexDisplayMode: .always))
                .cornerRadius(12)
                .padding(.vertical)
            }
        }
        .overlay(alignment: .bottom, content: {
            Button(action: {
                // 1. 图片保存在本地.
                // 2. 创建本地数据库
            }, label: {
                Text("Save")
                    .foregroundColor(Theme.color.title)
            })
            .padding()
            .withCapsuleBg(colors: [Theme.color.primaryBackgroundColor])
        })
        .navigationBarItems(trailing: Button(action: {
            print("保存")
        }, label: {
            Image(systemName: "icloud.and.arrow.up")
                .resizable()
        }))
    }
    
    func saveData() {
        var paths: [String] = []
        for data in camera.picDatas {
            let name = data.id.uuidString
            do {
                try  FileManager.default.setData(data: data.datas, name: name, type: .photo)
                paths.append(name)
            } catch(let error) {
                ToastManager.show(text: error.localizedDescription)
                break
            }
        }
        guard paths.count == camera.picDatas.count else { //保存图片失败
            for path in paths { ///移除已经保存的图片
                try? FileManager.default.removeItem(name: path, type: .photo)
            }
            return
        }
        // 存入数据库
        let ticData = TicProducter()
        ticData.userId = "\(UserService.userId)"
        ticData.date = dateFormatter.string(from: birthDate)
        ticData.subTitle = subTitle
        ticData.title = title
        ticData.tickets = paths
        CaseDBManager.shared.insetRecord(data: ticData)
        // 存入成功 
        route.backToRoot()
    }
    
}

#Preview {
    let camera = CaptureLogic()
    return EditCaseView()
        .environmentObject(camera)
}
